<script setup lang="ts">
import {onMounted, ref, toRaw, computed} from "vue";
import axios from "axios";
import {ElNotification} from "element-plus";
import {ServerHost, loginUser} from "@/main.js";
import {Refresh, Search, Timer, Upload} from "@element-plus/icons-vue";
import PostOrEditAgritainment from "@/components/agritainmentManage/PostOrEditAgritainment.vue";

const sellerOrderList = ref([])
const isLoadingList = ref(true)
const isEditDialogVisible = ref(false)
const selectedOrder = ref()

// 懒加载商家农家乐列表
const observerDiv = ref(null)
const hasLoad = ref(false)
onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        if (!hasLoad.value) {
          loadList()
        }
      }
    });
  });
  observer.observe(observerDiv.value);
})

const loadList = () => {
  console.log("开始获取农家乐列表")
  axios.get(`${ServerHost}/getAgritainmentList?sellerId=${loginUser.value.id}`)
      .then((res) => {
            if (res.status === 200) {
              sellerOrderList.value = res.data;
              ElNotification({
                title: '农家乐获取成功',
                type: 'success',
                position: 'bottom-right',
              })
              console.log(sellerOrderList.value)
              hasLoad.value = true
              isLoadingList.value = false
            } else {
              ElNotification({
                title: '订单获取失败',
                type: 'error',
                position: 'bottom-right',
              })
            }
          }
      )
}

const filterTableData = computed(() =>
    sellerOrderList.value.filter(order => {
      return order.id.includes(searchKey.value)
    })
)

// const onEditPolicy = (id: string) => {
//   console.log(id)
// }

const onRowClick = (row: any, column: any, event: Event) => {
  isEditDialogVisible.value = true

  // selectedPolicy.value = policyList.value.find((Policy: any) => {
  //   return Policy.id === row.id
  // })
  sellerOrderList.value.forEach((policy: any) => {
    if (policy.id === row.id) {
      // 深拷贝policy，防止子组件修改父组件数据
      selectedOrder.value = structuredClone(toRaw(policy))
      console.log(selectedOrder.value)
    }
  })
}

// watch(policyList, (newValue, oldValue) => {
//   console.log("数据变化了", newValue, oldValue);
// }, { deep: true });


const getIsSubmitDone = (value: string) => {
  isEditDialogVisible.value = !value
  loadList()
}

const searchKey = ref("")

const onSearchKeydown = (event: KeyboardEvent) => {
  if (event.key === "Enter") {
    // onSearch()
  }
}

const onSearch = () => {
  if (searchKey.value !== "") {
    // loadList()
  }
}

const onClearSearch = (id: string) => {
  // loadList()
}

const isAddDialogVisible = ref(false)
const expressOrder = ref()

</script>

<template>
  <div ref="observerDiv"/>
  <!--  忽略warn type="search" -->
  <div class="flex">
    <el-input type="text" v-model="searchKey" @keydown="onSearchKeydown" class="mb-2 mr-3"
              placeholder="输入名称、ID来搜索农家乐"
              :prefix-icon="Search" clearable @clear="onClearSearch">
      <template #append>
        <el-button :icon="Search" @click="onSearch"/>
      </template>
    </el-input>

    <el-button @click="isAddDialogVisible = true">
      <el-icon class="el-icon--left">
        <Upload/>
      </el-icon>
      上架农家乐
    </el-button>

    <el-button @click="loadList">
      <el-icon class="el-icon--left">
        <Refresh/>
      </el-icon>
      刷新列表
    </el-button>
  </div>

  <el-tag class="w-full">点击农家乐以编辑</el-tag>
  <!--  Table-->
  <!-- height: 减去导航栏、页脚、搜索栏等元素的高度 -->
  <el-table
      :data="filterTableData"
      height="calc(100vh - 120px - 140px)"
      empty-text="没有农家乐"
      v-loading="isLoadingList"
      :onRowClick="onRowClick">
    <el-table-column
        prop="id"
        label="农家乐编号"
    >
      <template #default="row">
        <p class="id">{{ row.row.id.split('-')[4] }}</p>
      </template>
    </el-table-column>

    <el-table-column
        prop="name"
        label="名称"
    >
    </el-table-column>

    <el-table-column
        prop="contact"
        label="联系人"
    >
    </el-table-column>
  </el-table>

  <!-- Edit Dialog -->
  <el-dialog
      v-model="isEditDialogVisible"
      title="编辑农家乐"
      width="500">
    <PostOrEditAgritainment type="edit" @getValue="getIsSubmitDone" :agritainment="selectedOrder"
                     :key="selectedOrder"/>
  </el-dialog>

  <!-- Add Dialog -->
  <el-dialog
      v-model="isAddDialogVisible"
      title="添加农家乐"
      width="500">
    <PostOrEditAgritainment type="new"/>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-table .el-table.row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.id {
  font-size: 0.7rem;
}
</style>
